package com.yueya.im.server;

import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import com.yueya.im.common.api.CmdHandler;
import com.yueya.im.common.api.ImSetting;
import com.yueya.im.server.actors.ImActorSystem;
import com.yueya.im.server.handler.DefaultBeatHandler;
import com.yueya.im.server.handler.SystemMsgHandler;
import com.yueya.im.server.netty.NettyServer;

import static com.yueya.im.common.constant.ImInfo.LIMIT_CODE_MAX;
import static com.yueya.im.common.constant.YueMsgCode.*;

public class ClusterNodeApp {
    private static Config root;
    public static void start(String conf, ImSetting setting){
        root = ConfigFactory.load(conf);
        ImActorSystem.getInstance().init(root,setting.getListener());
        NettyServer server = new NettyServer();
        Config nettyConfig = root.getConfig("akka").getConfig("netty");
        int port = nettyConfig.getInt("port");
        String mode = nettyConfig.getString("mode");
        boolean heartbeat = nettyConfig.getBoolean("hear_beat");
        setting.setHearBeatConfig(heartbeat);
        checkHandler(setting);
        server.start(setting,port,mode);
    }

    private static void checkHandler(ImSetting setting){
        setting.getHandlerMap().forEach((k,v)->{
            int code = Integer.parseInt(k);
            if(code < LIMIT_CODE_MAX){
                throw new IllegalArgumentException("请勿使用系统保留的消息类型码(0-100):"+code);
            }
        });
      if(setting.getHearBeatConfig()){
          //加入心跳消息处理器
          CmdHandler heartBeatHandler = new DefaultBeatHandler();
          setting.getHandlerMap().put(MSG_HEART_BEAT_PING+"",heartBeatHandler);
      }
      SystemMsgHandler msgHandler = new SystemMsgHandler();
      if(setting.getRestMsgListener()!=null){
          msgHandler.setListener(setting.getRestMsgListener());
      }
      setting.getHandlerMap().put(REST_MSG_POINT+"",msgHandler);
      setting.getHandlerMap().put(REST_MSG_GROUP+"",msgHandler);
    }

}
